import pymongo
from setting import *


class MongoServer:
    def __init__(self):
        self.client = pymongo.MongoClient(host=MONGO_HOST, port=MONGO_PORT)
        self.client['admin'].authenticate('admin', 'kake')

    def set_collection(self, collection_name):
        res = self.client['admin'].command(
            {'shardcollection': f"tyc_detail_html.{collection_name}", 'key': {'id': "hashed"}})
        self.collection = self.client[MONGO_DATABASE][collection_name]
        self.collection.create_index('id', unique=True)

    def process_item(self, item, treading_nema):
        try:
            self.collection.insert(dict(item))
            print(treading_nema, item)
        except pymongo.errors.DuplicateKeyError as e:
            print(f'{item["id"]} --> {item["name"]} --> 数据重复')
        return item

    def __del__(self):
        self.client.close()


def save_mongoDB(item, table_name, thread_name):
    client = pymongo.MongoClient(host=host, port=port)
    db = client['tyc_detail']
    # db.authenticate("tianyancha", "jueke")
    collection = db[table_name]
    collection.create_index('url_id', unique=True)
    try:
        collection.insert_one(item)
        print(f'{item["company_name"]} - {item["contact_info"]["company_phone"]} --> 数据保存成功')
    except pymongo.errors.DuplicateKeyError as e:
        print(e)
        print(f'{thread_name} -> {item["company_name"]} --> 数据重复')
    # for i in data:
    #     print(i)
    #     if i:
    #         db[table_name].insert_one(i)
    #     else:
    #         print('本次数据入库失败')
    # return L_itemId


if __name__ == '__main__':
    data = {"url_id": "123", "123": "567"}
    save_mongoDB(data, 'tianyanc')
